package cn.mandifal.pay.service.impl;

import cn.mandifal.pay.service.ZhiFuBaoPayService;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付宝支付服务层
 * @author shun
 */
@Service
public class ZhiFuBaoPayServiceImpl implements ZhiFuBaoPayService {
    /**
     * 支付宝支付
     * @param out_trade_no 商户订单号，商户网站订单系统中唯一订单号，必填
     * @param total_amount 付款金额，必填
     * @throws Exception
     */
    @Override
    public String pay(String out_trade_no,String total_amount) throws Exception {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //订单名称，必填
        String subject = new String("支付宝".getBytes("ISO-8859-1"),"UTF-8");
        //商品描述，可空
        String body = new String("二手网".getBytes("ISO-8859-1"),"UTF-8");
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\"15m\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //输出，返回的 result 是一个string 类型，里面有一些信息
        return result;
    }

    /**
     *  验证签名
     * @param requestParams 支付宝返回的参数
     * @return 返回 true 或 false
     * @throws Exception
     */
    @Override
    public Boolean checkSign( Map<String,String[]> requestParams) throws Exception {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            System.out.println("--------------"+name);
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        return  signVerified;
    }

    /**
     * 查询支付状态
     * @param out_trade_no 支付订单号
     * @param trade_no 支付宝流水订单号
     * @return
     */
    @Override
    public String queryPay(String out_trade_no, String trade_no) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no1 = new String(out_trade_no.getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no1 = new String(trade_no.getBytes("ISO-8859-1"),"UTF-8");
        //请二选一设置

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no1 +"\","+"\"trade_no\":\""+ trade_no1 +"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        return result;
    }

    /**
     * 根据支付支付宝流水号，退款（可部分退款）
     * @return
     */
    @Override
    public Boolean refund(Map map) throws Exception {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //得到支付宝流水号
        String trade_no = (String) map.get("trade_no");
        //得到退款金额
        String refund_amount = (String) map.get("refund_amount");
        //得到退款原因
        String refund_reason = (String) map.get("refund_reason");
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        //退款订单号就是订单详情 id
        String out_request_no = (String) map.get("orderItemId");

        alipayRequest.setBizContent("{\"trade_no\":\""+ trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");

        //请求并返回结果
        String result = alipayClient.execute(alipayRequest).getBody();
        //转换成 json 对象
        System.out.println(result);
        JSONObject jsonObject = JSON.parseObject(result);
        String alipay_trade_refund_response = jsonObject.getString("alipay_trade_refund_response");
        JSONObject jsonObject1 = JSON.parseObject(alipay_trade_refund_response);
        if ("10000".equals(jsonObject1.getString("code"))){
            return true;
        }else {
            return false;
        }
    }
}
